package com.yunquan.ohana.ui.weather.search

import androidx.databinding.ObservableField
import androidx.lifecycle.viewModelScope
import com.yunquan.ohana.base.binding.command.BindingAction
import com.yunquan.ohana.base.binding.command.BindingCommand
import com.yunquan.ohana.base.ui.ItemViewModel
import com.yunquan.ohana.db.DBWeatherLocation
import com.yunquan.ohana.entity.LocalLocationModel
import com.yunquan.ohana.entity.Location
import com.yunquan.ohana.entity.UserManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class WeatherSearchItemViewModel(viewModel: WeatherSearchViewModel) : ItemViewModel<WeatherSearchViewModel>(viewModel) {

    var data: Location? = null

    val name = ObservableField<String>()

    constructor(viewModel: WeatherSearchViewModel, data: Location) : this(viewModel) {
        this.data = data
        this.name.set(data.name)
    }

    val onPickClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            viewModel.viewModelScope.launch(Dispatchers.IO) {
                var bean = DBWeatherLocation.instance.selectOne(
                    "user_id = ? AND name = ?",
                    arrayOf(UserManager.instance.getUser()?.id.toString(), data!!.name!!)
                ) ?: LocalLocationModel()
                bean.locationId = data?.id
                bean.name = data?.name
                bean.longitude = data?.lon
                bean.latitude = data?.lat
                bean.timeZone = data?.tz
                bean.utcOffset = data?.utcOffset
                DBWeatherLocation.instance.saveOrUpdate(bean)
                withContext(Dispatchers.Main) {
                    viewModel.changeCity.value = data
                }
            }
        }
    })
}